package com.example.weight.greenSeasons.SolidLiquid;
import com.example.weight.R;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.view.View;

import com.example.weight.greenSeasons.flocculation.xuningguzhang;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;
import android.content.Intent;
import android.util.Log;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.weight.config.Config;
import com.example.weight.util.WeightActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

public class chuzha7_2 extends AppCompatActivity implements View.OnClickListener{

    private TitleBar titleBar;
    //日期
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");// HH:mm:ss
    Date incomingDate = new Date(System.currentTimeMillis());
    private TextView worm_incoming_incomeDate;

    Calendar calendar= Calendar.getInstance(Locale.CHINA);
    //备注
    private EditText remark;
    //出沙量
//    private TextView worm_income_weight;
    //用户、抄表人
    private String name, role, factory;
    //
    private TextView testid;
    //出渣时间
    private TextView chuzhaTime;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chuzha7_2);

        //页面返回按钮
        titleBar=findViewById(R.id.titleBar);
        titleBar.setOnTitleBarListener(new OnTitleBarListener() {
            @Override
            public void onLeftClick(View v) {
                chuzha7_2.this.finish();
            }
            @Override
            public void onTitleClick(View v) {
            }
            @Override
            public void onRightClick(View v) {
            }
        });

        //日期
        worm_incoming_incomeDate = findViewById(R.id.worm_incoming_incomeDate);
        worm_incoming_incomeDate.setText(simpleDateFormat.format(incomingDate));
        //备注
        remark = findViewById(R.id.worm_incoming_remark);
        //出沙量
//        worm_income_weight = findViewById(R.id.worm_income_weight);
        //用户和职责
        Intent previousIntent = getIntent();
        name = previousIntent.getStringExtra("name");
        role = previousIntent.getStringExtra("role");
        factory = previousIntent.getStringExtra("factory");

        //出渣时间
        chuzhaTime=findViewById(R.id.chuzhaTime);
        chuzhaTime.setOnClickListener(this);

        //testid=findViewById(R.id.testid);
        //testid.setText(name+role);
        //获取当天最新一条数据
        RequestQueue queue = Volley.newRequestQueue(this);
        String url = Config.url + "/sjq/solidliquidProduceFlatmaterialNew/getlast" + "?factory=" + factory;
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            JSONObject data;
                            if(jsonObject.get("data")!=null && !jsonObject.get("data").toString().equals("null")){
                                data = jsonObject.getJSONObject("data");
                                if (!data.isNull("id") && data.getString("factory").equals(factory)) {
//                                    worm_income_weight.setText(data.getString("sandOutput"));
                                    remark.setHint(data.getString("remarks1"));
                                    chuzhaTime.setHint(data.getString("updateTime"));
                                    Toast.makeText(chuzha7_2.this,
                                            "今日已填写此表", Toast.LENGTH_SHORT).show();
                                }
                            }else{
                                //SimpleDateFormat DateFormat = new SimpleDateFormat("yyyy-MM-dd mm:ss");
                                SimpleDateFormat DateFormat = new SimpleDateFormat("HH:mm");
                                Date nowtime = new Date(System.currentTimeMillis());
                                chuzhaTime.setText(DateFormat.format(nowtime));
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(chuzha7_2.this,
                        "获取信息失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        queue.add(stringRequest);
    }

    /**
     * 时间选择
     * @param activity
     * @param themeResId
     * @param tv
     * @param calendar
     */
    public static void showTimePickerDialog(Activity activity, int themeResId, final TextView tv, Calendar calendar) {
        // Calendar c = Calendar.getInstance();
        // 创建一个TimePickerDialog实例，并把它显示出来
        // 解释一哈，Activity是context的子类
        new TimePickerDialog( activity,themeResId,
                // 绑定监听器
                new TimePickerDialog.OnTimeSetListener() {
                    @Override
                    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                        tv.setText(hourOfDay + ":" + minute);
                    }
                }
                // 设置初始时间
                , calendar.get(Calendar.AM_PM)
                , calendar.get(Calendar.MINUTE)
                // true表示采用24小时制
                ,true).show();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.chuzhaTime:
                showTimePickerDialog(this,  2, chuzhaTime, calendar);
                break;
            default:
                break;
        }
    }

    @SuppressLint("ResourceType")
    public void chooseRestoreDate(View view) {
        Calendar calendar=Calendar.getInstance();
        new DatePickerDialog(chuzha7_2.this,2,
                new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year,
                                          int month, int day) {
                        // TODO Auto-generated method stub
                        Integer mYear = year;
                        Integer mMonth = month;
                        Integer mDay = day;
                        // 更新EditText控件日期 小于10加0
                        new TimePickerDialog(chuzha7_2.this, 2,new TimePickerDialog.OnTimeSetListener() {
                            @Override
                            public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                                Integer mhourOfDay  = hourOfDay;   //得到小时
                                Integer mminute  = minute;            //得到分钟
                                //  这个方法是得到选择后的 小时、分钟，分别对应着三个参数 —   hourOfDay、minute
                                chuzhaTime.setText(new StringBuilder()
                                        .append(mYear)
                                        .append("-")
                                        .append((mMonth + 1) < 10 ? "0"
                                                + (mMonth + 1) : (mMonth + 1))
                                        .append("-")
                                        .append((mDay < 10) ? "0" + mDay : mDay)
                                        .append(" ")
                                        .append(String.format("%02d",hourOfDay)).append(":").append(String.format("%02d",minute)));
                            }
                        }, calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MONTH), true).show();

                    }
                }, calendar.get(Calendar.YEAR), calendar
                .get(Calendar.MONTH), calendar
                .get(Calendar.DAY_OF_MONTH)).show();
    }
    /**
     * 称重接口
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        String weight = data.getStringExtra("weight");
//        worm_income_weight.setText(weight);
    }
    public void goWeight(View view) {
        Intent intent = new Intent(chuzha7_2.this, WeightActivity.class);
        startActivityForResult(intent, 1);
    }

    //提交按钮
    public void save(View view) {
//        if (worm_income_weight.getText().toString().equals("")) {
//            Toast.makeText(this, "请填写出砂量", Toast.LENGTH_SHORT).show();
//            return;
//        }
        /*
        if(remark.getText().toString().equals("")) {
            Toast.makeText(this, "请填写备注", Toast.LENGTH_SHORT).show();
            return;
        }*/
        new AlertDialog.Builder(this)
                .setTitle("确定保存吗？")
                .setCancelable(false)
                .setNegativeButton("取消", ((dialog, which) ->
                        Toast.makeText(this, "取消保存", Toast.LENGTH_SHORT).show()))
                .setPositiveButton("确定", (dialog, which) -> {
                    //提交请求
                    RequestQueue queue = Volley.newRequestQueue(this);
                    String url = Config.url + "/sjq/solidliquidProduceFlatmaterialNew/add";
                    StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                            new Response.Listener<String>() {
                                @Override
                                public void onResponse(String response) {
                                    Log.d("jy", response);
                                    try {
                                        JSONObject jsonObject = new JSONObject(response);
                                        String code = jsonObject.getString("code");

                                        if (code.startsWith("2"))
                                            Toast.makeText(chuzha7_2.this,
                                                    "保存成功", Toast.LENGTH_SHORT).show();
                                        else
                                            Toast.makeText(chuzha7_2.this,
                                                    "保存失败", Toast.LENGTH_SHORT).show();
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Toast.makeText(chuzha7_2.this,
                                    "保存失败" + error.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }) {
                        @Override
                        protected Map<String, String> getParams() throws AuthFailureError {
                            Map<String, String> map=new HashMap<>();
                            map.put("date", worm_incoming_incomeDate.getText().toString());
                            map.put("updateTime",chuzhaTime.getText().toString());
//                            map.put("sandOutput", worm_income_weight.getText().toString());
                            map.put("operator", name);
                            map.put("remarks1", remark.getText().toString());
                            map.put("factory", factory);
                            return map;
                        }
                    };
                    stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                            DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                    queue.add(stringRequest);
                })
                .show();
    }
}